<template>
  <div class="list-table">
    <div class="area-header">
      <span class="area-header-title">{{ $t('出资人缴款') }}</span>
    </div>
    <el-form ref="queryForm" :model="queryParams" :inline="true" :rules="queryRules">
      <el-form-item v-if="!this.$route.query.id" :label="$t('基金名称')" prop="fundId">
        <MainBodySelect
          v-model="queryParams.fundId"
          parameters="fund"
          :disabled="this.$route.query.id"
        />
      </el-form-item>
      <el-form-item :label="$t('出资人')" prop="investorName">
        <el-input v-model="queryParams.investorName" :placeholder="$t('出资人')" @keyup.enter.native="queryHandle" />
      </el-form-item>

      <el-form-item :label="$t('缴款时间')">
        <DatePicker
          v-model="dateRange"
          type="daterange"
        />
      </el-form-item>

      <el-form-item v-if="fundDataType === 'fund'" :label="$t('Call款期次')" prop="callPeriodName">
        <el-input v-model="queryParams.callPeriodName" :placeholder="$t('Call款期次')" @keyup.enter.native="queryHandle" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t("搜索") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("重置") }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-if="queryParams.lpId === undefined"
          v-hasPermi="['fund:lppayment:edit']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="addHandle"
        >{{ $t("新增") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-show="queryParams.lpId === undefined"
          v-hasPermi="['fund:lppayment:edit']"
          type="warning"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >{{ $t('导入') }}</el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          v-hasPermi="['fund:lppayment:export']"
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="exportHandle"
        >{{ $t("导出") }}</el-button>
      </el-col>-->
    </el-row>

    <el-table ref="payTable" v-loading="loading" :data="fundLpPaymentList" :show-summary="true" :summary-method="getSummaries" border :row-key="getRowKeys" @sort-change="sortColumnSearch">
      <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
        <template slot-scope="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column v-if="queryParams.lpId === undefined" :label="$t('出资人')" sortable align="center" prop="investorName" min-width="200" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span class="link-type" @click="updateHandle(scope.row)">{{ scope.row.investorName }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="queryParams.lpId !== undefined" :label="$t('基金名称')" sortable align="center" prop="fundName" min-width="200" :show-overflow-tooltip="true" />
      <el-table-column v-if="fundDataType === 'fund'" :label="$t('Call款期次')" sortable align="center" prop="callPeriodName" show-overflow-tooltip min-width="120" />
      <el-table-column :label="$t('缴款时间')" sortable align="center" prop="payDate" show-overflow-tooltip min-width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('缴款金额') + $t('金额单位')" sortable header-align="center" align="right" prop="payMoney" show-overflow-tooltip min-width="120">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.payMoney, 'w') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('操作')" fixed="right" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['fund:lppayment:edit']"
            size="small"
            type="text"
            :icon="queryParams.lpId !== undefined ? 'el-icon-view' : 'el-icon-edit'"
            @click="updateHandle(scope.row)"
          >{{ queryParams.lpId === undefined ? $t('修改'): $t('查看') }}</el-button>
          <el-button
            v-show="queryParams.lpId === undefined"
            v-hasPermi="['fund:lppayment:remove']"
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="deleteHandle(scope.row)"
          >{{ $t('删除') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改出资人缴款对话框 -->
    <el-dialog :title="title" :visible.sync="fundLpPaymentLoading" :destroy-on-close="true" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <fundLpPaymentForm ref="fundLpPaymentForm" :other-btn-hide="otherBtnHide" />
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog v-if="queryParams.lpId === undefined" :title="upload.title" :visible.sync="upload.open" width="400px" :close-on-click-modal="false" :lock-scroll="false" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          {{ $t('将文件拖到此处，或') }}
          <em>{{ $t('点击上传') }}</em>
        </div>
        <div slot="tip" class="el-upload__tip" style="color:red">{{ $t('提示：仅允许导入“xls”或“xlsx”格式文件！') }}</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="info" class="el-icon-download el-icon--right" style="font-size:12px;float:left;" @click="fetchTemplate">
          {{ $t('下载模板') }}
        </el-button>
        <el-button @click="upload.open = false">{{ $t("取消") }}</el-button>
        <el-button type="primary" @click="submitFileForm">{{ $t("确定") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFundLpPayment, delFundLpPayment, getFundLpPaymentSum } from '@/api/fund/lpPayment/fundLpPayment'
import fundLpPaymentForm from './fundLpPaymentForm.vue'
import MainBodySelect from '@/components/MainBodySelect/index'
import { getToken } from '@/utils/auth'
import { downLoadExcel } from '@/utils/excelDownload'
import { fundDataType } from '@/api/fund/fundBase'
export default {
  components: {
    fundLpPaymentForm,
    MainBodySelect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 出资人缴款表格数据
      fundLpPaymentList: [],
      fundLpPaymentSum: {},
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      fundLpPaymentLoading: false,
      otherBtnHide: false,
      // 获取基金数据类型，如果是spv则不展示缴款
      fundDataType: 'fund',
      // 查询参数
      queryParams: {
          investId: undefined,
          payDate: undefined,
          lpId: undefined,
          investorName: undefined,
          callPeriodName: undefined,
          fundId: this.$route.query.id ? this.$route.query.id : undefined,
          isAsc: undefined,
          orderByColumns: undefined,
          pageNum: 1,
          pageSize: 10
      },
      queryRules: {},
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/lpPayment/fundLpPayment/importData?fundId=' + this.$route.query.id
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 时间区间
      dateRange: [],
      // 出资人下拉
      investOptions: []
    }
  },
  created() {
      this.getList(undefined)
      this.getFundDataType(this.$route.query.id)
  },
  methods: {
    /** 查询出资人缴款列表 */
    getList(data) {
      if (data !== undefined && data !== null && data.lpId !== undefined && data.lpId !== '') {
          this.queryParams.lpId = data.lpId
          this.queryParams.fundId = data.fundId
          this.otherBtnHide = true
      }
      this.loading = true
      getFundLpPaymentSum(this.addDateRange(this.queryParams, this.dateRange)).then(res => {
        this.fundLpPaymentSum = res.data
      })
      listFundLpPayment(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.fundLpPaymentList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    investNameFormat(row) {
      return this.selectDictLabel(this.investOptions, row.investId)
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        fundId: undefined,
        investId: undefined,
        subscriptionAmount: undefined,
        payDate: undefined,
        payMoney: undefined,
        callPeriod: undefined,
        callMoney: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    queryHandle() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.dateRange = []
      this.queryHandle()
    },
    /** 新增按钮操作 */
    addHandle() {
      this.fundLpPaymentLoading = true
      this.title = this.$t('添加出资人缴款')
      this.$nextTick(() => {
        this.$refs.fundLpPaymentForm.init(null)
      })
    },
    /** 修改按钮操作 */
    updateHandle(row) {
      this.fundLpPaymentLoading = true
      this.title = this.$t('修改出资人缴款')
      this.$nextTick(() => {
        // 调用form页面的 init 方法初始化数据
        this.$refs.fundLpPaymentForm.init(row)
      })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return delFundLpPayment(row.id)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('删除成功'))
      }).catch(function() {
      })
    },
    /** 导出按钮操作 */
    exportHandle() {
      downLoadExcel('/lpPayment/fundLpPayment/export', this.queryParams)
    },
    /** 导入按钮操作 */
    handleImport() {
      if (!this.$route.query.id) {
        if (this.queryParams.fundId) {
          this.queryRules.fundId = [{ required: false, message: this.$t('请选择一只基金') }]
          const url = this.upload.url
          if (url) {
            this.upload.url = url.substring(0, url.indexOf('undefined')) + this.queryParams.fundId
          }
          this.handleImportOpen()
        } else {
          this.queryRules.fundId = [{ required: true, message: this.$t('请选择一只基金') }]
          this.$refs['queryForm'].validate()
        }
      } else {
        this.handleImportOpen()
      }
    },
    handleImportOpen() {
      this.upload.title = this.$t('出资人缴款导入')
      this.upload.open = true
    },
    // 文件上传中处理
    handleFileUploadProgress() {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 下载模板
    fetchTemplate() {
      var href1 = window.location.href
      var href2 = this.$route.path
      var url = href1.substring(0, href1.indexOf(href2))
      window.location.href = url + '/template/investorContributionsImport.xlsx'
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    // 获取基金数据类型，如果是spv则不展示缴款
    getFundDataType(fundId) {
      fundDataType(fundId).then(res => {
        this.fundDataType = res.data
      })
    },
    getRowKeys(row) {
      return row.id === null || row.id === undefined ? new Date().getTime() : row.id
    },
    sortColumnSearch(column) {
      if (column.order !== null) {
        if (column.order === 'descending') {
          this.queryParams.isAsc = 'desc'
          this.queryParams.orderByColumns = column.prop
        } else {
          this.queryParams.isAsc = 'asc'
          this.queryParams.orderByColumns = column.prop
        }
      } else {
        this.queryParams.isAsc = undefined
        this.queryParams.orderByColumns = undefined
        this.$refs.payTable.clearSort()
      }
      this.getList()
    },
    // 合计
    getSummaries(param) {
      const { columns } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
        } else if (index === 4) {
          sums[index] = this.moneyFormat(this.fundLpPaymentSum.payMoney, 'w')
        } else {
          sums[index] = ''
        }
      })
      return sums
    }
  }
}
</script>
